/*
 * ExpUm.java
 *
 * Created on 04/03/2010, 23:45:29
 */
package br.ufrn.dca.scontrol.view;

import br.ufrn.dca.controle.QuanserClient;
import br.ufrn.dca.controle.QuanserClientException;
import br.ufrn.dca.scontrol.control.ExpUmControl;
import br.ufrn.dca.scontrol.control.ListenerAuxiliar;
import br.ufrn.dca.scontrol.control.ListenerTanque;
import java.awt.Color;
import java.awt.Paint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TimerTask;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * First experience
 * @author Marco Olimpio
 */
public class ExpUm extends javax.swing.JInternalFrame {

    ListenerTanque tListen;
    ListenerAuxiliar tAux;
    
    Timer t;//checagem principal
    Timer tGrafico;//checagem de grafico
    Timer tCheck;//checagem de valores

    Vector valoresTanque1;
    Vector valoresTanque2;
    XYSeries series;//dataset
    XYSeriesCollection[] datasets;
    JFreeChart chart;
    XYDataset xyDataset;
    boolean GrafThreadFlag;
    Vector tempos;

    Tanks3DCanvas Tanks3d = new Tanks3DCanvas();
    
    /** Creates new form ExpUm */
    public ExpUm() {

        tempos = new Vector();
        initComponents();
        GrafThreadFlag = false;
        datasets = new XYSeriesCollection[2];
        //===============

        series = new XYSeries("Nível de Fluido");
        series.clear();

        XYSeries t1 = new XYSeries("Tanque 1");
        XYSeries t2 = new XYSeries("Tanque 2");
        datasets[0] = new XYSeriesCollection(t1);
        datasets[0].addSeries(t2);

        XYSeries s = new XYSeries("Tanque 1");

        xyDataset = new XYSeriesCollection(series);//tanque 1

        chart = ChartFactory.createTimeSeriesChart("Subida de Nível de Fluido", "Tempo", "Valor da Coluna",
                xyDataset,  true, true, false);
        //chart = ChartFactory.create("xx", "TEE", "te", datasets, PlotOrientation.HORIZONTAL, true, false, false);
        XYPlot xyPlot = (XYPlot) chart.getPlot();
        xyPlot.setBackgroundPaint(new Color(255, 255, 255));
        xyPlot.setDomainGridlinePaint(new Color(0,0,0));

        ChartPanel frame = new ChartPanel(chart);

        chart.setBackgroundPaint(new Color(240, 245, 250));
        //DefaultChartPanel newPanelChart = new DefaultChartPanel(50);
        jPanel1.add(frame);
        frame.setVisible(true);

        jPanel3.add(Tanks3d);
        Tanks3d.setSize(jPanel3.getPreferredSize());

        tListen = new ListenerTanque();
        t = new Timer(100, tListen);

        ActionListener actCheck = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                realizarChecagem();
            }
        };
        tCheck = new Timer(100,actCheck);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel8 = new javax.swing.JPanel();
        AlturaColunaInput = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        PassoVoltInput = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        TensaoInicialInput = new javax.swing.JFormattedTextField();
        jPanel9 = new javax.swing.JPanel();
        jButton_Testar = new javax.swing.JButton();
        jButton_Abortar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("Experiência 1");
        setDoubleBuffered(true);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Estado do(s) Tanque(s)"));
        jPanel3.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                jPanel3ComponentResized(evt);
            }
        });
        jPanel3.addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                jPanel3AncestorResized(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 316, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 495, Short.MAX_VALUE)
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Gráfico - Primeiro Tanque"));
        jPanel1.setLayout(new java.awt.BorderLayout());

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configurações de Controle"));

        jCheckBox1.setText("Realizar todos os testes?");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jLabel5.setText("Alarme de Escoamento");

        jLabel6.setText("Vazão:");

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCheckBox1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addContainerGap(109, Short.MAX_VALUE))
        );

        AlturaColunaInput.setColumns(2);
        try {
            AlturaColunaInput.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        AlturaColunaInput.setText("15");

        jLabel1.setText("Altura da Coluna (em cm)");

        jLabel2.setText("Passo (em volts)");

        try {
            PassoVoltInput.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#.#")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        PassoVoltInput.setText("0.2");

        jLabel3.setText("Tensão Inicial (em volts)");

        try {
            TensaoInicialInput.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#.##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        TensaoInicialInput.setText("1.75");

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addContainerGap())
            .addComponent(TensaoInicialInput, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
            .addComponent(PassoVoltInput, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
            .addComponent(AlturaColunaInput, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(AlturaColunaInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PassoVoltInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TensaoInicialInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        jButton_Testar.setLabel("Testar");
        jButton_Testar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_TestarActionPerformed(evt);
            }
        });

        jButton_Abortar.setText("Abortar");
        jButton_Abortar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AbortarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addComponent(jButton_Testar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton_Abortar, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGap(3, 3, 3)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Testar)
                    .addComponent(jButton_Abortar)))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Tensão u (volts)", "Tempo (segundos)", "Km", "Vazão"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                        .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_TestarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_TestarActionPerformed
        if(Double.parseDouble(AlturaColunaInput.getText().toString())<(Double)28.0){
            if(Double.parseDouble(PassoVoltInput.getText().toString())<(Double)3.0){
                if(Double.parseDouble(TensaoInicialInput.getText().toString())<(Double)3.0){
                    
                    tListen.setValorTensaoInicial(Double.parseDouble(TensaoInicialInput.getText()));
                    tListen.setValorColuna(Double.parseDouble(AlturaColunaInput.getText()));
                    tListen.takeOffsetValues();
                    calcTensoesTeste(Double.parseDouble(TensaoInicialInput.getText()), Double.parseDouble(PassoVoltInput.getText()));

                    t.start();
                    tCheck.start();
                    
                    GrafThreadFlag = true;

                    ActionListener act = new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            atualizaGrafico();
                        }
                    };
                    tGrafico = new Timer(100, act);
                    tGrafico.start();

                }else{
            JOptionPane.showMessageDialog(null, "Valores invalidos!");}
            }else{
            JOptionPane.showMessageDialog(null, "Valores invalidos!");
            }
        }else{
            JOptionPane.showMessageDialog(null, "Valores invalidos!");
        }
    }//GEN-LAST:event_jButton_TestarActionPerformed

    private void jButton_AbortarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AbortarActionPerformed
        GrafThreadFlag = false;
        tListen.setEscrito(false);
        tListen.killClient();
        t.stop();
        tCheck.stop();
        //tGrafico.stop();
    }//GEN-LAST:event_jButton_AbortarActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        if(jCheckBox1.isSelected()){
            jButton_Testar.setText("Realizar testes");
        }else{
            jButton_Testar.setText("Testar");
        }
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jPanel3AncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_jPanel3AncestorResized
        Tanks3d.setSize(jPanel3.getSize());
        Tanks3d.setCanvasSize(jPanel3.getSize());
    }//GEN-LAST:event_jPanel3AncestorResized

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        Tanks3d.setSize(jPanel3.getSize());
        Tanks3d.setCanvasSize(jPanel3.getSize());
    }//GEN-LAST:event_formComponentResized

    private void jPanel3ComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jPanel3ComponentResized
        Tanks3d.setSize(jPanel3.getSize());
        Tanks3d.setCanvasSize(jPanel3.getSize());
    }//GEN-LAST:event_jPanel3ComponentResized

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField AlturaColunaInput;
    private javax.swing.JFormattedTextField PassoVoltInput;
    private javax.swing.JFormattedTextField TensaoInicialInput;
    private javax.swing.JButton jButton_Abortar;
    private javax.swing.JButton jButton_Testar;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    public boolean getGrafThreadFlag(){
        return GrafThreadFlag;
    }

    public void setGrafThreadFlag(boolean f){
        this.GrafThreadFlag = f;
    }

    public void atualizaGrafico(){
        //pega valor do timer principal
        //verifica se é zero
        //pega o tempo

        Tanks3d.setColuna01(tListen.getValorCorrenteT1() * 6.25);
        Tanks3d.setColuna02(tListen.getValorCorrenteT2() * 6.25);
        
        if(tListen.istInicialSetado()){
            Long iValue = tListen.getTempoInicial();
        }
        if(tListen.istFinalSetado()){
            Long fValue = tListen.getTempoFinal();
            tListen.settInicialSetado(false);
        }
        Vector tensoes;
        Vector tempo;
        int limite;
        tensoes = tListen.getValoresTensaoT1();
        tempo = tListen.getValoresTempo();
        limite = 100;
        try{
            series.clear();
            //JOptionPane.showMessageDialog(null, "entrei no graficooooo");
            //if(!(tensoes.size() != tempo.size())){
                //if(limite < tensoes.size()){

//                    for(int i = tensoes.size() ; i > limite ; i--){
//                        series.add(Double.parseDouble(tempo.get(i).toString()),Double.parseDouble(tensoes.get(i).toString()));
//                    }
//                    xyDataset = new XYSeriesCollection(series);
//                    chart = ChartFactory.createXYLineChart("Subida de Nível de Fluido", "Tempo", "Valor da Coluna",
//                    xyDataset, PlotOrientation.VERTICAL, true, true, false);
                    //for(int ii =0 ; ii<tensoes.size() ; ii++){
                    //    series.add(Double.parseDouble(tempo.get(ii).toString()),Double.parseDouble(tensoes.get(ii).toString()));
                    //}
                    /*
                     series = tListen.getSeries();
                    System.out.println(series.getItemCount());
                    System.out.println(series);
                    XYSeriesCollection xyDataset1 = new XYSeriesCollection(series);
                    JFreeChart chrt = ChartFactory.createXYLineChart("Subida de Nível", "Tempo", "Valor da Coluna", xyDataset1, PlotOrientation.HORIZONTAL, true, true, false);
                    chart = chrt;

                     */
                    //chart = ChartFactory.createXYLineChart("Subida de Nível de Fluido", "Tempo", "Valor da Coluna",
                    //xyDataset, PlotOrientation.VERTICAL, true, true, false);
                    
                    //chart.

                //}
                //else{
//                    for(int i = tensoes.size() ; i > limite ; i--){
//                        series.add(Double.parseDouble(tempo.get(i).toString()),Double.parseDouble(tensoes.get(i).toString())*6.25);
//                    }
//                    xyDataset = new XYSeriesCollection(series);
//                    chart = ChartFactory.createXYLineChart("Subida de Nível de Fluido", "Tempo", "Valor da Coluna",
//                    xyDataset, PlotOrientation.VERTICAL, true, true, false);
                //}
            //}else
                //System.out.println("Valores de tensões e de tempos não combinam");
        }catch(IndexOutOfBoundsException ex){
            System.out.println("Problemas de indexaçao");
            ex.printStackTrace();
        }
    }

    /**
     * Realizar a checagem de inicialização e etc
     */
    public void realizarChecagem(){

        if(tListen.istFinalSetado()){
            Long tFinal = tListen.getTempoFinal();
            Long tInicial = tListen.getTempoInicial();
            String duracao = ""+((tFinal-tInicial)/1000);
            double tDur = (double)0.00;
            if(((tFinal-tInicial)/1000)>(double)0.00){
                tDur = ((tFinal-tInicial)/1000);
                System.out.println("-------------------------Duracao: "+tDur);
                tempos.add(tDur);
            }
            //if(tListen.getCounter()==tListen.getTensoesAplicadas().size()-1){
                //((DefaultTableModel)jTable1.getModel()).addRow(new Object[]{"1.0",duracao,km});
                /*DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                model.setNumRows(0);//limpa a tabela
                if(Long.parseLong(duracao)>0){
                    for (int i = 0; i < tListen.getTensoesAplicadas().size(); i++) {
                        String km = ""+(medirKm(Double.parseDouble(tListen.getTensoesAplicadas().get(i).toString()),Double.parseDouble(duracao)));
                        model.addRow(new Object[]{tListen.getTensoesAplicadas().get(i),tDur,km});
                        System.out.println("===========================================================\n==========================================================="+km);
                    }
                }*/
            //}
            if(tListen.getCounter()==tListen.getTensoesAplicadas().size()-1){
                DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                model.setNumRows(0);
                double somaKm=0;
                for (int i = 0; i < tempos.size(); i++) {
                    double km = medirKm(Double.parseDouble(tListen.getTensoesAplicadas().get(i).toString()),
                            Double.parseDouble(tempos.get(i).toString()));

                    somaKm+=km;

                    double diametro = (double)4.445;//diametro cubo
                    double volume = Math.PI*Math.pow(diametro/2, 2)*Double.parseDouble(AlturaColunaInput.getText());//volume do cilindro
                    double vazao = volume/Double.parseDouble(tempos.get(i).toString());
                    model.addRow(new Object[]{tListen.getTensoesAplicadas().get(i),tempos.get(i),km,vazao});

                }
                model.addRow(new Object[]{"","Km Medio: ",somaKm/tempos.size()});
            }
        }
        if(tListen.istInicialSetado()){
            
        }
    }

    public double medirKm(double tensao, double tempo){
        double km;
        double vazao;
        double tensaoBomba = 5*tensao;
        double diametro = (double)4.445;//diametro cubo
        double volume = Math.PI*Math.pow(diametro/2, 2)*Double.parseDouble(AlturaColunaInput.getText());//volume do cilindro
        vazao = volume/tempo;
        km = (vazao/tensaoBomba);
        return km;
    }

    public void calcTensoesTeste(double tInicial, double passo){
        Vector tensoesAplicadas = new Vector();
        if (jCheckBox1.isSelected()) {
            double q = 3.00 - tInicial;
            int qTestes = (int) (q / passo);//quantidade de testes
            String resu = "";
            for (int i = 0; i <= qTestes; i++) {
                tensoesAplicadas.add(tInicial + (passo * i));
                resu += tInicial + (passo * i);
            }
            //System.out.println("Tensoes aplicadas: " + resu);
        } else {
            tensoesAplicadas.add(tInicial);
        }
        tListen.setTensoesAplicadas(tensoesAplicadas);
    }
}

